﻿using B.S.Base.Read.API.Application.Command;
using MediatR;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;
using System.Linq;

namespace B.S.Base.Read.API.Application.CommandHandLer
{
    public class GetDeptAccountComandHandLer : IRequestHandler<GetDeptAccountComand, APIResult<List<object>>>
    {
        private readonly IBaseRepostiy<AccountModel> _accountModel;
        private readonly IBaseRepostiy<UserRoleModel> _userRoleModel;
        private readonly IBaseRepostiy<DeptModel> _DeptModel;
        private readonly IBaseRepostiy<RoleModel> _RoleModel;
        public GetDeptAccountComandHandLer(IBaseRepostiy<AccountModel> accountModel, IBaseRepostiy<UserRoleModel> userRoleModel, IBaseRepostiy<DeptModel> deptModel, IBaseRepostiy<RoleModel> RoleModel)
        {
            this._accountModel = accountModel;
            this._userRoleModel = userRoleModel;
            this._DeptModel = deptModel;
            this._RoleModel = RoleModel;
        }

        public Task<APIResult<List<object>>> Handle(GetDeptAccountComand request, CancellationToken cancellationToken)
        {
            var accounts = _accountModel.GetAll().ToList();
            var userRoles = _userRoleModel.GetAll().ToList();
            var roles = _RoleModel.GetAll().ToList();
            var depts = _DeptModel.GetAll().ToList();

            // 查询指定部门中角色为"总经理"的用户
            var resultList = from account in accounts
                            join userRole in userRoles on account.AccountId equals userRole.AccountId
                            join role in roles on userRole.RoleId equals role.RoleId
                            join dept in depts on account.DeptId equals dept.DeptId
                            where role.RoleName == "总经理" && account.DeptId == request.DeptId
                            select new
                            {
                                AccountId = account.AccountId,
                                AccountName = account.AccountName,
                                DeptId = account.DeptId,
                                Deptstring = dept.Deptstring,
                                RoleId = userRole.RoleId,
                                RoleName = role.RoleName,
                                UserRoleId = userRole.UserRoleId
                            };

            return Task.FromResult(new APIResult<List<object>>
            {
                Code = ResultCode.Ok,
                Data = resultList.Cast<object>().ToList(),
                Message = "获取成功"
            });
        }
    }
}
